<script lang="ts" setup>
const { width, height, count } = defineProps({
  width: {
    type: Number,
    default: 75
  },
  height: {
    type: Number,
    default: 36
  },
  count: {
    type: Number,
    default: 4
  }
})

const codeArr: string[] = [
  'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h',
  'j',
  'k',
  'm',
  'n',
  'p',
  'q',
  'r',
  's',
  't',
  'u',
  'v',
  'w',
  'x',
  'y',
  'z',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9'
]
let showCode: string = ''
const draw = () => {
  showCode = ''
  //获取到canvas
  const canvas: any = document.getElementById('canvas')
  if (!canvas) {
    return
  }
  let context = canvas.getContext('2d')
  canvas.width = width
  canvas.height = height
  //获取到数组的长度
  let aLength = codeArr.length
  for (let i = 0; i < count; i++) {
    //获取到随机的索引值
    let j = Math.floor(Math.random() * aLength)
    // 产生0~30之间的随机弧度
    let deg = (Math.random() * 30 * Math.PI) / 180
    //得到随机的一个字符并保存
    let txt = codeArr[j]
    showCode += txt.toUpperCase()
    //文字在canvas上的x坐标
    let x = 3 + i * 16
    //文字在canvas上的y坐标
    let y = height / 2 + Math.random() * 8
    context.font = 'bold 25px 微软雅黑'

    context.translate(x, y)
    context.rotate(deg)

    context.fillStyle = randomColor()
    context.fillText(txt, 0, 0)

    context.rotate(-deg)
    context.translate(-x, -y)
  }

  //验证码上显示线条
  for (let i = 0; i <= 5; i++) {
    context.strokeStyle = randomColor()
    context.beginPath()
    context.moveTo(Math.random() * width, Math.random() * height)
    context.lineTo(Math.random() * width, Math.random() * height)
    context.stroke()
  }

  //验证码上显示小点
  for (let i = 0; i <= 30; i++) {
    context.strokeStyle = randomColor()
    context.beginPath()
    let x = Math.random() * width
    let y = Math.random() * height
    context.moveTo(x, y)
    context.lineTo(x + 1, y + 1)
    context.stroke()
  }
  sendEmoji(showCode)
}

const randomColor = () => {
  //得到随机的颜色值
  const r = Math.floor(Math.random() * 256)
  const g = Math.floor(Math.random() * 256)
  const b = Math.floor(Math.random() * 256)
  return 'rgb(' + r + ',' + g + ',' + b + ')'
}

onMounted(() => {
  draw()
})

const emit = defineEmits(['getCode'])
const sendEmoji = (code: string) => {
  emit('getCode', code)
}
</script>

<template>
  <a id="canvasWrapper" href="javascript:" style="background-color: #fff" @click="draw">
    <canvas id="canvas" />
  </a>
</template>

<style lang="scss" scoped></style>
